<?php

namespace Drupal\shusy_banner\Entity;

use Entity;

class ShusyBannerItem extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $banner_id;

  public $image;

  public $link;

  public $weight = 0;

  public $status = 1;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_banner_item');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }

    if (!empty($this->image)) {
      $dir = "public://shusy_banner_item/image/" . format_date(REQUEST_TIME, 'custom', 'Y/m/d');
      $result = file_prepare_directory($dir);
      if (empty($result)) {
        drupal_mkdir($dir, 0777, TRUE);
      }
      $file = file_load($this->image);
      if (!empty($file)) {
        $file->status = 1;
        file_save($file);
        $fid = $this->image;
        $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
        $file = file_move($file, "{$dir}/{$fid}.{$ext}");
        file_usage_add($file, 'shusy_banner_item', 'image', $file->fid);
      }
    }

    return parent::save();
  }

  function getLinkOptions() {
    return [
      0 => '无跳转',
    ];
  }
}
